import { VNode } from "vue";

/**
 * 深度获取
 * @param dataIndex  string | string[]
 * @param data  Object
 * @returns unknow
 */
export function getValueByModel(dataIndex: string| string[], data: any): any {

    if(!data) return data;
  
    if (Array.isArray(dataIndex) && dataIndex.length === 1) {
      return data[dataIndex[0]];
    } else if(Array.isArray(dataIndex)){
      let key = dataIndex[0];
      return getValueByModel(dataIndex.slice(1), data[key]);
    }
    else{
        return data[dataIndex];
    }
  }
  
  /**
   * 深度设置
   * @param dataIndex string | string[]
   * @param data Object
   * @param newValue unknow
   * @returns 
   */
  export function setValueByModel (dataIndex: string| string[], data: any, newValue: unknown) {
    if(Array.isArray(dataIndex) && dataIndex.length === 1) {
      data[dataIndex[0]] = newValue;
    }
    else if(Array.isArray(dataIndex)){
      let key = dataIndex[0]
      if (data[key] === undefined) data[key] = {} // 自动填补数据层级，对深层级的 赋值 或 粘贴 场景及其重要！
      data[key] = setValueByModel(dataIndex.slice(1), data[key], newValue);
    }
    else{
      data[dataIndex] = newValue;
    }
    return data;
  }

/**
 * 检测插槽内容是否是空的
 * @param target 
 * @returns 
 */
  export function checkTargetSlotIsEmpty (target: any) {
    return !target?.filter((node: VNode) => node.children).length
  }


/**
 * 计算grid布局的列属性设置 style 对象
 * @param columns 
 * @returns `{ grid-template-columns: ... }`
 */
export function calcGridColumns(columns: Column[]){
  const widths: (number|string)[] = [];
  columns?.forEach(col => {
      if (col.width === undefined || col.width === null) widths.push('auto')
      else if (col.width === parseFloat(`${col.width}`)) widths.push(col.width + 'px')
      else widths.push(col.width)
  })
  return {
      'grid-template-columns': `${widths.join(' ')}`
  }
}


export function awaitTime(time: number) {
  return new Promise((reslove) => {
    setTimeout(() => reslove(true), time)
  })
}